const Strategy = require('passport-strategy')
const JSCODE_SESSION_URL = 'https://api.weixin.qq.com/sns/jscode2session'
const request = require('request-promise')
const config = require('config')

/**
 * Usage new WxAppStrategy((wechatInfo) => {})
 */
class WxAppStrategy extends Strategy {
  constructor (verify) {
    super()
    this.name = 'wxapp'
    this._verify = verify
  }
  async authenticate (req, options) {
    // get user by sid
    const { code, userInfo } = req.body
    const uri = `${JSCODE_SESSION_URL}?appid=${config.wechat.appid}&secret=${config.wechat.secret}&js_code=${code}&grant_type=authorization_code`
    let { openid, session_key, unionid } = await request({ json:true, uri })
    
    if (!code || !userInfo) {
      this.fail('code or userInfo not exists')
      return
    }
    userInfo.openId = openid
    console.log('wxUserInfo', userInfo)
    // get access token
    // const wxUserInfo = req.$wxUserInfo
    // if (!wxUserInfo) {
    //   this.fail({ message: options.badRequestMessage || 'Missing wxUserInfo' }, 400);
    // }
    this._verify(userInfo, (err, user, info) => {
      if (err) {
        return this.error(err)
      }
      if (user) {
        this.success(user)
      } else {
        this.fail(info)
      }
    })
  }
}

module.exports = WxAppStrategy